﻿using Adp;
using Adp.Common;
using Adp.Core.Attribute;
using Microsoft.AspNetCore.Mvc;
using Yqd.Core;
using Yqd.Enm;
using Yqd.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yqd.Controllers.Filter;
using Newtonsoft.Json.Linq;
using System.IO;
using OfficeOpenXml;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class ZLDHomeController : Controller
    {
        YqdContext ctx;

        DdService ddService;

        public ZLDHomeController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        //总体效能
        //[HttpPost]
        [User]
        public ActionResult GetAllEvaluate()
        {
            var p = Form.GetInt("platform", 0);
            //var UnitCode = Form.GetString("UnitCode", p == 1 ? "330782000000" : WxUser.LogonInfo.UnitCode);
            var UnitCode = Form.GetString("UnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "330782000000");
            var Area = Form.GetString("Area");
            var dt = DateTime.Now;
            var YiWu = ctx.Yqd_Rank.OrderByDescending(it => it.ResultTime).FirstOrDefault(it => it.ResultTime > dt && it.UnitCode == UnitCode);
            var Name = YiWu.Name;
            var Score = 0.0;
            var Count = 0;
            var WC = 0;
            var ZC = 0;
            var YJ = 0;
            var ZH = 0;
            var Tactic = 0;
            if (Area.Trim() == "")
            {

                Score = YiWu.Score;
                Count = YiWu.Count;
                WC = YiWu.WC;
                ZC = YiWu.ZC;
                YJ = YiWu.YJ;
                ZH = YiWu.ZH;
                Tactic = YiWu.Tactic;
            }
            else if (Area == "330000000000")
            {

                Score = YiWu.Score_330000;
                Count = YiWu.Count_330000;
                WC = YiWu.WC_330000;
                ZC = YiWu.ZC_330000;
                YJ = YiWu.YJ_330000;
                ZH = YiWu.ZH_330000;
                Tactic = YiWu.Tactic_330000;
            }
            else if (Area == "330700000000")
            {

                Score = YiWu.Score_330700;
                Count = YiWu.Count_330700;
                WC = YiWu.WC_330700;
                ZC = YiWu.ZC_330700;
                YJ = YiWu.YJ_330700;
                ZH = YiWu.ZH_330700;
                Tactic = YiWu.Tactic_330700;
            }
            else if (Area == "330782000000")
            {

                Score = YiWu.Score_330782;
                Count = YiWu.Count_330782;
                WC = YiWu.WC_330782;
                ZC = YiWu.ZC_330782;
                YJ = YiWu.YJ_330782;
                ZH = YiWu.ZH_330782;
                Tactic = YiWu.Tactic_330782;
            }

            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Name,// YiWu.Name,
                    Score,//YiWu.Score,
                    Count,//YiWu.Count,
                    WC,//YiWu.WC,
                    ZC,//YiWu.ZC,
                    YJ,//YiWu.YJ,
                    ZH,//YiWu.ZH
                    Tactic
                }
            });
        }
        //历史趋势
        //[HttpPost]
        [User]
        public ActionResult GetAllEvaluateLog()
        {
            var p = Form.GetInt("platform", 0);
            //var UnitCode = Form.GetString("UnitCode", p == 1 ? "330782000000" : WxUser.LogonInfo.UnitCode);
            var UnitCode = Form.GetString("UnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "330782000000");
            var Area = Form.GetString("Area");
            var dt = DateTime.Now;

            var YiWuList = ctx.Yqd_Rank.Where(it => it.UnitCode == UnitCode && it.ResultTime < dt).OrderByDescending(it => it.ResultTime).ToList();

            return this.ToJson(new
            {
                success = true,
                data = YiWuList.Select(it => new
                {
                    Score = Area.Trim() == "" ? it.Score : (Area == "330000000000" ? it.Score_330000 : (Area == "330700000000" ? it.Score_330700 : it.Score_330782)),
                    DateTime = it.ResultTime.ToString("MM月dd日")
                })
            });

        }
        //单位效能指数
        //[HttpPost]
        [User]
        public ActionResult GetUnitRank()
        {
            var Size = Form.GetInt("Size", 250);
            var pType = Form.GetInt("pType", 0);
            var px = Form.GetString("px", "desc");
            var Area = Form.GetString("Area");

            var MaxResultTime = ctx.Yqd_Rank.OrderByDescending(it => it.ResultTime).FirstOrDefault()?.ResultTime;
            var RankList = new List<Yqd_Rank>();


            if (Area.Trim() == "")
            {
                RankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime && it.Tactic > 0 && it.Count > 0).ToList();
                if (px == "asc")
                {
                    RankList = RankList.OrderBy(it => pType == 0 ? it.Score : it.Count).Take(Size).ToList();
                }
                else
                {
                    RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score : it.Count).ThenByDescending(it => pType == 0 ? it.Count : it.Score).Take(Size).ToList();
                }
            }
            else if (Area == "330000000000")
            {
                RankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime && it.Tactic_330000 > 0 && it.Count_330000 > 0).ToList();
                if (px == "asc")
                {
                    RankList = RankList.OrderBy(it => pType == 0 ? it.Score_330000 : it.Count_330000).Take(Size).ToList();
                }
                else
                {
                    RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score_330000 : it.Count_330000).ThenByDescending(it => pType == 0 ? it.Count_330000 : it.Score_330000).Take(Size).ToList();
                }
                RankList = RankList.Select(it => new Yqd_Rank
                {
                    Name = it.Name,
                    Count = it.Count_330000,
                    Score = it.Score_330000,
                    Tactic = it.Tactic_330000,
                    UnitCode = it.UnitCode
                }).ToList();


            }
            else if (Area == "330700000000")
            {
                RankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime && it.Tactic_330700 > 0 && it.Count_330700 > 0 && it.Tactic_330700 > 0).ToList();
                if (px == "asc")
                {
                    RankList = RankList.OrderBy(it => pType == 0 ? it.Score_330700 : it.Count_330700).Take(Size).ToList();
                }
                else
                {
                    RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score_330700 : it.Count_330700).ThenByDescending(it => pType == 0 ? it.Count_330700 : it.Score_330700).Take(Size).ToList();
                }
                RankList = RankList.Select(it => new Yqd_Rank
                {
                    Name = it.Name,
                    Count = it.Count_330700,
                    Score = it.Score_330700,
                    Tactic = it.Tactic_330700,
                    UnitCode = it.UnitCode
                }).ToList();

            }
            else if (Area == "330782000000")
            {
                RankList = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime && it.Tactic_330782 > 0 && it.Count_330782 > 0).ToList();
                if (px == "asc")
                {
                    RankList = RankList.OrderBy(it => pType == 0 ? it.Score_330782 : it.Count_330782).Take(Size).ToList();
                }
                else
                {
                    RankList = RankList.OrderByDescending(it => pType == 0 ? it.Score_330782 : it.Count_330782).ThenByDescending(it => pType == 0 ? it.Count_330782 : it.Score_330782).Take(Size).ToList();
                }
                RankList = RankList.Select(it => new Yqd_Rank
                {
                    Name = it.Name,
                    Count = it.Count_330782,
                    Score = it.Score_330782,
                    Tactic = it.Tactic_330782,
                    UnitCode = it.UnitCode
                }).ToList();

            }

            //if (px == "asc")
            //{
            //    RankList = RankList.OrderBy(it => pType == 0 ? it.Score : it.Count).ToList();
            //}

            var arr = new ArrayList();
            foreach (var r in RankList)
            {
                arr.Add(new
                {
                    r.RankID,
                    r.Name,
                    r.Count,
                    r.Score,
                    r.Tactic,
                    r.UnitCode
                });
            }

            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        public ActionResult GetRank()
        {
            var RankID = Form.GetInt("RankID", 0);
            var Rank = ctx.Yqd_Rank.FirstOrDefault(it => it.RankID == RankID);
            if (Rank == null)
            {
                return this.ToJson(new
                {
                    success = true,
                    msg = "效能信息为空"
                });

            }

            var zhTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.滞后 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var yjTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.预警 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var zcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.正常推进 && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var wcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.已完成 && it.IsShow && it.IsShow && (it.LeaderUnitCode == Rank.UnitCode)).OrderByDescending(it => it.CreateTime).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();


            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Rank.Name,
                    ResultTime = Rank.ResultTime.ToString("yyyy-MM-dd"),
                    Rank.Score,
                    Tactic = Rank.UnitCode == "330782000000" ? "--" : Rank.Tactic.ToString(),
                    Rank.UnitCode,
                    ZHTask = new
                    {
                        Type = Enm.任务状态.滞后.ToString(),
                        ZH = Rank.ZH,
                        list = zhTask,
                    },
                    YJTask = new
                    {
                        Type = Enm.任务状态.预警.ToString(),
                        YJ = Rank.YJ,
                        //Area.Trim() == "" ? yiwu.YJ : (Area == "330000000000" ? yiwu.YJ_330000 : (Area == "330700000000" ? yiwu.YJ_330700 : yiwu.YJ_330782)),
                        list = yjTask,
                    },
                    ZCTask = new
                    {
                        Type = Enm.任务状态.正常推进.ToString(),
                        ZC = Rank.ZC, //Area.Trim() == "" ? yiwu.ZC : (Area == "330000000000" ? yiwu.ZC_330000 : (Area == "330700000000" ? yiwu.ZC_330700 : yiwu.ZC_330782)),
                        list = zcTask,
                    },
                    WCTask = new
                    {
                        Type = Enm.任务状态.已完成.ToString(),
                        WC = Rank.WC,// Area.Trim() == "" ? yiwu.WC : (Area == "330000000000" ? yiwu.WC_330000 : (Area == "330700000000" ? yiwu.WC_330700 : yiwu.WC_330782)),
                        list = wcTask,
                    }
                },

            });

        }
        //历史效能评价报告
        //[HttpPost]
        [User]
        public ActionResult TaskLog()
        {
            var Take = Form.GetInt("Take", 3);
            var p = Form.GetInt("platform", 0);
            //var UnitCode = Form.GetString("UnitCode", p == 1 ? "330782000000" : WxUser.LogonInfo.UnitCode);
            var UnitCode = Form.GetString("UnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "330782000000");
            var Area = Form.GetString("Area");
            var MaxResultTime = ctx.Yqd_Rank.OrderByDescending(it => it.ResultTime).FirstOrDefault()?.ResultTime;
            var yiwu = ctx.Yqd_Rank.Where(it => it.ResultTime == MaxResultTime).FirstOrDefault(it => it.UnitCode == UnitCode);
            var zhTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.滞后 && it.IsShow && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? (1 == 1) : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var yjTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.预警 && it.IsShow && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? (1 == 1) : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var zcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.正常推进 && it.IsShow && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? (1 == 1) : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            var wcTask = ctx.Yqd_Task.Where(it => it.TaskStatus == (int)Enm.任务状态.已完成 && it.IsShow && (UnitCode != "330782000000" ? it.LeaderUnitCode == UnitCode : UnitCode == "330782000000") && (Area.Trim() == "" ? (1 == 1) : (it.FAreaCode == Area))).OrderByDescending(it => it.CreateTime).Take(Take).Select(it => new
            {
                it.TaskName,
                TaskID = it.TaskID.ToString()
            }).ToList();
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    ZHTask = new
                    {
                        Type = Enm.任务状态.滞后.ToString(),
                        //ZH= yiwu.ZH,
                        ZH = Area.Trim() == "" ? yiwu.ZH : (Area == "330000000000" ? yiwu.ZH_330000 : (Area == "330700000000" ? yiwu.ZH_330700 : yiwu.ZH_330782)),
                        list = zhTask,
                    },
                    YJTask = new
                    {
                        Type = Enm.任务状态.预警.ToString(),
                        YJ = Area.Trim() == "" ? yiwu.YJ : (Area == "330000000000" ? yiwu.YJ_330000 : (Area == "330700000000" ? yiwu.YJ_330700 : yiwu.YJ_330782)),
                        list = yjTask,
                    },
                    ZCTask = new
                    {
                        Type = Enm.任务状态.正常推进.ToString(),
                        ZC = Area.Trim() == "" ? yiwu.ZC : (Area == "330000000000" ? yiwu.ZC_330000 : (Area == "330700000000" ? yiwu.ZC_330700 : yiwu.ZC_330782)),
                        list = zcTask,
                    },
                    WCTask = new
                    {
                        Type = Enm.任务状态.已完成.ToString(),
                        WC = Area.Trim() == "" ? yiwu.WC : (Area == "330000000000" ? yiwu.WC_330000 : (Area == "330700000000" ? yiwu.WC_330700 : yiwu.WC_330782)),
                        list = wcTask,
                    }
                }
            });
        }
        //[HttpPost]
        //获取全景透视工作类别
        [User]
        public IActionResult GetTaskType()
        {
            var list = ctx.Yqd_TaskType.Where(it => it.ParentID == 0).OrderByDescending(it => it.Tactic).Select(it => new { text = it.TypeName, value = it.TypeID }).ToList();
            return this.ToJson(new
            {
                success = true,
                data = list,

            });
        }
        //[HttpPost]
        //获取当前任务列表的牵头单位列表
        [User]
        public IActionResult GetTaskUnit()
        {
            var TaskTypeID = Form.GetLong("TaskTypeID");
            var Status = Form.GetInt("Status", 0);
            var AreaCode = Form.GetString("AreaCode");
            var key = Form.GetString("key");
            var Leader = Form.GetString("Leader", "王健");
            var Link = Form.GetString("Link");

            var EvaluateInfo = Form.GetString("EvaluateInfo");

            var where = "SELECT  u.UnitCode, u.Name, u.Tactic FROM Yqd_Task AS t INNER JOIN Yqd_Unit AS u ON t.LeaderUnitCode = u.UnitCode WHERE t.IsShow = 1";
            if (Status > 0)
            {
                where += " and t.TaskStatus = {0}";
            }


            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and t.FAreaCode={1}";
            }

            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim(t.TaskName))) like {2}";
            }

            if (Leader != "王健")
            {
                where += " and  u.Leader={3}  ";
            }

            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == EvaluateInfo && it.IsShow).Select(it => it.TaskID).ToList();
                if (einfos.Count > 0)
                {
                    where += " and t.TaskID in (" + string.Join(",", einfos) + ") ";
                }

            }


            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From " + Link + "  ) ";
                }

            }


            if (TaskTypeID > 0)
            {
                var TaskTypeIDs = ctx.Yqd_TaskType.Where(it => it.ParentID == TaskTypeID).Select(it => it.TypeID).ToArray();
                var sql = "";
                where += " and (";

                foreach (var id in TaskTypeIDs)
                {
                    sql += (string.IsNullOrEmpty(sql) ? "" : " or ") + "  t.TaskIDPath like '%" + id + "%' ";

                }
                where += sql;
                where += " )";
            }

            where += " GROUP BY u.UnitCode, u.Name, u.Tactic";
            where += " ORDER BY u.Tactic";
            var list = ctx.Database.SqlQuery<Unit>(where, Status, AreaCode, "%" + key.ToLower().Trim() + "%", Leader);

            return this.ToJson(new
            {
                success = true,
                data = list
            });
        }
        //[HttpPost]
        //获取当前任务列表
        [User]
        public IActionResult GetTaskList()
        {
            //已完成 = 1,
            //正常推进 = 2,
            //预警 = 3,
            //滞后 = 4
            //var Year = Form.GetInt("Year");
            var TaskTypeID = Form.GetLong("TaskTypeID");
            var Status = Form.GetInt("Status", 0);
            var p = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("LeaderUnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "");
            var Leader = Form.GetString("Leader", "王健");
            var AreaCode = Form.GetString("AreaCode");
            var key = Form.GetString("key");
            var cp = Form.GetInt("cp", 1);
            var size = Form.GetInt("size", 10);
            var EvaluateInfo = Form.GetString("EvaluateInfo");
            var Link = Form.GetString("Link");
            var State = Form.GetInt("State", 0);
            if (cp < 1)
            {
                cp = 1;
            }
            var where = " IsShow =1 ";
            if (Status > 0)
            {
                where += " and TaskStatus={0}";
            }

            if (TaskTypeID > 0)
            {
                var TaskTypeIDs = ctx.Yqd_TaskType.Where(it => it.ParentID == TaskTypeID).Select(it => it.TypeID).ToArray();
                var sql = "";
                where += " and (";

                foreach (var id in TaskTypeIDs)
                {
                    sql += (string.IsNullOrEmpty(sql) ? "" : " or ") + "  TaskIDPath like '%" + id + "%' ";

                }
                where += sql;
                where += " )";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                where += " and LeaderUnitCode={1}";
            }

            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and FAreaCode={2}";
            }


            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([TaskName]))) like {3}";
            }
            if (Leader != "王健")
            {
                where += " and LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={4} ) ";
            }
            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == EvaluateInfo && it.IsShow).Select(it => it.TaskID).ToList();
                if (einfos.Count > 0)
                {
                    where += " and TaskID in (" + string.Join(",", einfos) + ") ";
                }

            }

            if (State > 0)
            {
                switch (State)
                {
                    case 30:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where Status=30 or Status=40)";
                        break;
                    case 60:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where Status>10 and Status!=40)";
                        break;
                    case 70:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where Status>10)";
                        break;
                    case 80:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where IsDeal=1)";
                        break;
                    case 90:
                        where += " and TaskID not in (select TaskID from Yqd_ExactSupervise)";
                        break;
                    case 100:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where IsLb=0 and TaskID not in(select TaskID from Yqd_ExactSupervise where IsLb=0 and Status!=40))";
                        break;
                    default:
                        where += " and TaskID in (select TaskID from Yqd_ExactSupervise where Status=" + State + ")";
                        break;
                }
            }
            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_Supervise_10")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where SuperviseType = 10 ) ";
                }
                else if (Link == "Yqd_Supervise_20")
                {
                    where += " and TaskID in (Select TaskID From Yqd_Supervise Where SuperviseType = 20 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From  " + Link + "  ) ";
                }

            }

            var (totalcount, data) = ctx.Database.SqlPager<Yqd_Task>((cp - 1) * size, size, "*", where, "[CreateTime] desc,ID desc", Status, LeaderUnitCode, AreaCode, "%" + key.ToLower().Trim() + "%", Leader);
            var taskid = data.Select(it => it.TaskID).ToList();
            var ys = ctx.Yqd_Supervise.Where(it => taskid.Contains(it.TaskID)).ToList();
            var dc = ctx.Yqd_ExactSupervise.Where(it => taskid.Contains(it.TaskID)).ToList();
            var r = WxUser.LogonInfo.Role;
            return this.ToJson(new
            {
                success = true,
                totalcount,
                IsAdmin = r.Any(it => it == 角色类型.管理员),
                data = data.Select(m => new
                {
                    ID = m.ID.ToString(),
                    TaskID = m.TaskID.ToString(),
                    m.TaskName,
                    m.FAreaCode,
                    UpdateTime = m.UpdateTime.ToString("yyyy-MM-dd"),
                    CreateTime = m.CreateTime.ToString("yyyy-MM-dd"),
                    TaskPath = m.TaskPath.Split("/")[0],
                    isDB = ys.Any(it => it.TaskID == m.TaskID && it.SuperviseType == 督导类型.钉办),
                    isDD = ys.Any(it => it.TaskID == m.TaskID && it.SuperviseType == 督导类型.督导),
                    isDC = dc.Any(it => it.TaskID == m.TaskID),
                    m.LeaderUnitName,
                    m.TaskStatus
                })
            });
        }

        //[HttpPost]
        //获取任务统计
        [User]
        public IActionResult GetTaskStatusTJ()
        {
            var TaskTypeID = Form.GetLong("TaskTypeID");
            var Status = Form.GetInt("Status", 0);
            var p = Form.GetInt("platform", 0);
            var LeaderUnitCode = Form.GetString("LeaderUnitCode", p == 2 ? WxUser.LogonInfo.UnitCode : "");
            //var LeaderUnitCode = Form.GetString("LeaderUnitCode");
            var key = Form.GetString("key");
            var Leader = Form.GetString("Leader", "王健");
            var EvaluateInfo = Form.GetString("EvaluateInfo");
            var AreaCode = Form.GetString("AreaCode");
            var Link = Form.GetString("Link");



            var where = "SELECT   TaskStatus, COUNT(*) AS Num FROM Yqd_Task WHERE IsShow = 1";
            if (Status > 0)
            {
                where += " and TaskStatus = {0}";
            }
            if (TaskTypeID > 0)
            {
                var TaskTypeIDs = ctx.Yqd_TaskType.Where(it => it.ParentID == TaskTypeID).Select(it => it.TypeID).ToArray();
                var sql = "";
                where += " and (";

                foreach (var id in TaskTypeIDs)
                {
                    sql += (string.IsNullOrEmpty(sql) ? "" : " or ") + "  TaskIDPath like '%" + id + "%' ";

                }
                where += sql;
                where += " )";
            }
            if (!string.IsNullOrWhiteSpace(LeaderUnitCode))
            {
                where += " and LeaderUnitCode={1}";
            }

            if (!string.IsNullOrWhiteSpace(AreaCode))
            {
                where += " and FAreaCode={2}";
            }

            if (key.Trim() != "")
            {
                where += " and lower(ltrim(rtrim([TaskName]))) like {3}";
            }

            if (Leader != "王健")
            {
                where += " and LeaderUnitCode in (Select UnitCode From Yqd_Unit Where Leader={4} ) ";
            }

            if (Link.Trim() != "")
            {
                if (Link == "Yqd_QuotaTable")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 1 ) ";

                }
                else if (Link == "Yqd_QuotaMsg")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaMsg Where IsShow = 1 ) ";
                }
                else if (Link == "Yqd_QuotaPlan")
                {
                    where += " and TaskID in (Select TaskID From Yqd_QuotaTable Where TState = 2 ) ";
                }
                else
                {
                    where += " and TaskID in (Select TaskID From " + Link + "  ) ";
                }

            }
            if (EvaluateInfo.Trim() != "" && Status == 3)
            {
                var einfos = ctx.Yqd_EvaluateInfo.Where(it => it.TaskStatus == 3 && it.DataTable == EvaluateInfo && it.IsShow).Select(it => it.TaskID).ToList();
                if (einfos.Count > 0)
                {
                    where += " and TaskID in (" + string.Join(",", einfos) + ") ";
                }

            }

            where += " GROUP BY TaskStatus";
            where += " ORDER BY TaskStatus";
            var list = ctx.Database.SqlQuery<TaskStatusTJ>(where, Status, LeaderUnitCode, AreaCode, "%" + key.ToLower().Trim() + "%", Leader).ToList();

            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Count = list.Sum(it => it.Num),
                    WC = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.已完成)?.Num ?? 0,
                    ZC = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.正常推进)?.Num ?? 0,
                    YJ = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.预警)?.Num ?? 0,
                    ZH = list.FirstOrDefault(it => it.TaskStatus == (int)Enm.任务状态.滞后)?.Num ?? 0,

                }
            });
        }
        //[HttpPost]    
        //获取任务概况
        [User]
        public IActionResult GetTaskInfo()
        {
            var TaskID = Form.GetLong("TaskID");
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务不存在"
                });
            }
            //var P = ctx.Yqd_Person.FirstOrDefault(it=>it.TaskID==TaskID&& it.PersonType==5&&it.IsShow);
            //// 3任务维护员 5分管领导 6部门联络员
            //var W = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 3 && it.IsShow);
            //var L = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 6 && it.IsShow);
            var P = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 5);
            // 3任务维护员 5分管领导 6部门联络员
            var W = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 3);
            var L = ctx.Yqd_Person.FirstOrDefault(it => it.TaskID == TaskID && it.PersonType == 6);
            var EResult = ctx.Yqd_EvaluateInfo.Where(it => it.TaskID == TaskID && it.IsShow && it.TaskStatus > 2).Select(it => new
            {
                TaskStatusName = Enum.GetName(typeof(任务状态), it.TaskStatus),
                it.TaskStatus,
                it.TFieldName,
                it.Evaluate,
            }).ToList();
            var ys = ctx.Yqd_Supervise.Where(it => it.TaskID == TaskID).ToList();
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Task.TaskName,
                    Task.LeaderUnitName,
                    Task.ReformTarget,
                    Task.TaskPath,
                    Task.TaskStatus,
                    Leader = P?.PersonName,
                    Weihu = W?.PersonName,
                    Lianluo = L?.PersonName,
                    isDB = ys.Any(it => it.SuperviseType == 督导类型.钉办),
                    isDD = ys.Any(it => it.SuperviseType == 督导类型.督导),
                    ErrorId= ctx.Yqd_TaskError.FirstOrDefault(it => it.TaskID == Task.TaskID)?.ID??0,
                  //  isError = ctx.Yqd_Supervise.Any(it => it.TaskID == Task.TaskID),
                    TaskStatusName = Enum.GetName(typeof(任务状态), Task.TaskStatus),
                    EResult,

                }
            });
        }

        [User]
        public IActionResult GetTaskTitle()
        {
            var TaskID = Form.GetLong("TaskID");
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务不存在"
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = new
                {
                    Task.TaskName
                }
            });
        }
        //[HttpPost]
        //获取任务指标
        [User]
        public IActionResult GetTaskQuota()
        {
            var TaskID = Form.GetLong("TaskID");
            var QuotaList = ctx.Yqd_Quota.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var Milestone = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var qml = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var arr = new ArrayList();
            foreach (var Q in QuotaList)
            {
                var qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                arr.Add(new
                {
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    MList = qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }),
                    IsMsg = qml.Any(it => it.QuotaCode == Q.QuotaCode && it.IsShow)
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        //[HttpPost]
        //获取工作计划
        [User]
        public IActionResult GetTaskPlan()
        {
            var TaskID = Form.GetLong("TaskID");
            var PlanList = ctx.Yqd_TaskPlan.Where(it => it.TaskID == TaskID).OrderBy(it => it.EndTime).ToList();
            var arr = new ArrayList();
            foreach (var p in PlanList)
            {
                arr.Add(new
                {
                    p.MilestoneTime,
                    p.PlanName,
                    p.CompleteDesc,
                    p.PlanStatus
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        //[HttpPost]
        //获取指标预警提醒
        [User]
        public IActionResult GetQuotaMsg()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var qmlist = ctx.Yqd_QuotaMsg.Where(it => it.QuotaCode == QuotaCode && it.IsShow).ToList();
            var arr = new ArrayList();
            foreach (var qm in qmlist)
            {
                arr.Add(new
                {
                    qm.ds,
                    qm.Msg
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }


        [User]
        public IActionResult GetQuotaFieldList()
        {
            var list = ctx.Yqd_QuotaField.ToList();

            var arr = new ArrayList();

            foreach (var f in list)
            {
                arr.Add(new
                {
                    Fname = f.FieldName,
                    Fid = f.FieldID
                });
            }
            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }
        [User]
        public IActionResult AddQuotaTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var FieldIDs = Form.GetString("FieldIDs");
            var TableID = Form.GetInt("TableID");
            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode && it.IsShow);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }

            var table = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.TableID == TableID);
            if (table == null)
            {
                var model = new Yqd_QuotaTable();
                model.TaskID = Quota.TaskID;
                model.QuotaCode = Quota.QuotaCode;
                model.FieldIDs = FieldIDs;
                model.TableType = Enm.清单类别.设置清单;
                model.Instime = DateTime.Now;
               // model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.TState = Enm.审核状态.同意;
                ctx.Yqd_QuotaTable.Add(model);
            }
            else
            {
                table.FieldIDs = FieldIDs;
                table.TableType = Enm.清单类别.设置清单;
                table.TState = Enm.审核状态.同意;
                // table.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
            }



            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        [User]
        public IActionResult AddQuotaNoplanTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var TableID = Form.GetInt("TableID");

            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode && it.IsShow);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }

            var table = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.TableID == TableID);
            if (table == null)
            {
                var model = new Yqd_QuotaTable();
                model.TaskID = Quota.TaskID;
                model.QuotaCode = Quota.QuotaCode;
                model.FieldIDs = "";
                model.TableType = Enm.清单类别.无清单;
                model.Instime = DateTime.Now;
               // model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                model.TState = Enm.审核状态.同意;
                ctx.Yqd_QuotaTable.Add(model);
            }
            else
            {
                table.FieldIDs = "";
                table.TableType = Enm.清单类别.无清单;
                table.Instime = DateTime.Now;
                // table.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                table.TState = Enm.审核状态.同意;
            }

            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public IActionResult GetQuotaTable()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var QuotaTable = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            //var Fieldlist = ctx.Yqd_QuotaField.OrderByDescending(it => it.Tactic).ToList();
            //var FieldIDs = Fieldlist.Select(it => new
            //{
            //    it.FieldID,
            //    it.FieldName
            //}).ToList();
            if (QuotaTable == null)
            {
                return this.ToJson(new
                {
                    success = true
                });
            }
            var arr = new ArrayList();
            return this.ToJson(new
            {
                success = true,
            
                data = new
                {
                    QuotaTable.TState,
                    QuotaTable.TableID,
                    QuotaTable.TableType
                }
            });


        }
        [User]
        public IActionResult EditQuotaTableState()
        {
            var TState = (Enm.审核状态)Form.GetInt("TState");
            var QuotaCode = Form.GetString("QuotaCode");
            var Quota = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            Quota.TState = TState;
            if (TState == Enm.审核状态.退回 && Quota.TableType == Enm.清单类别.无清单)
            {
                Quota.TableType = Enm.清单类别.不可设置无清单;
            }
            Quota.EmployeeCode= WxUser.LogonInfo.EmployeeCode;
            var ret=ctx.SaveChanges();
            if (ret > 0 && TState == Enm.审核状态.退回 && !string.IsNullOrEmpty(Quota.AddEmployeeCode))
            {
                var user = ctx.Yqd_User.FirstOrDefault(it=>it.EmployeeCode== Quota.AddEmployeeCode);
                var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == Quota.TaskID);
                var Q = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == Quota.QuotaCode && it.IsShow);
                var text = string.Format("您提交的“{0}”任务中的“{1}”指标清单不符合要求，已退回，请重新提交。（未完成提交，任务状态将变成预警）",task.TaskName,Q.QuotaName);
                var msg = ddService.GetNotification_Text(text);
                var model = new Yqd_MsgLog();
                model.MsgType = 2;
                model.bizMsgId = Quota.TableID + "_" + DateTime.Now.Minute;
                model.receiverIds = user.AccountId.ToString();
                model.msg = msg;
                model.Result = string.IsNullOrWhiteSpace(user.AccountId.ToString()) ? "接收人为空" : ddService.workNotification("", user.AccountId.ToString(), Quota.TableID + "_" + DateTime.Now.Minute, msg, ""); 
                model.Instime = DateTime.Now;
                ctx.SaveChanges();
            }
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public IActionResult AddQuotaPlan()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var PlanData = Form.GetString("PlanDatas").ToJArray();
            var Quota = ctx.Yqd_Quota.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            if (Quota == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }
            var lst = new List<Yqd_QuotaPlan>();
            var pids = new List<int>();
            var index = 0;
            var qp = ctx.Yqd_QuotaPlan.Where(it => it.QuotaCode == QuotaCode);
            foreach (var info in PlanData)
            {
                
                //var PState = (Enm.清单状态)int.Parse(info["PState"].ToString());
                var model = new Yqd_QuotaPlan
                {
                    Name = info["Name"] == null ? "" : info["Name"].ToString(),
                    Street = info["Street"] == null ? "" : info["Street"].ToString(),
                    LinkMan = info["LinkMan"] == null ? "" : info["LinkMan"].ToString(),
                    LinkTel = info["LinkTel"] == null ? "" : info["LinkTel"].ToString(),
                    Unit = info["Unit"] == null ? "" : info["Unit"].ToString(),
                    ProgressPlan = info["ProgressPlan"] == null ? "" : info["ProgressPlan"].ToString(),
                    ProgressInfo = info["ProgressInfo"] == null ? "" : info["ProgressInfo"].ToString(),
                    Remarks = info["Remarks"] == null ? "" : info["Remarks"].ToString(),
                    PlanData = info.ToString(),
                    PState = (Enm.清单状态)int.Parse(info["PState"].ToString()),
                    Tactic= index
                };

                if (!string.IsNullOrEmpty(model.Remarks) || !string.IsNullOrEmpty(model.ProgressInfo) || !string.IsNullOrEmpty(model.ProgressPlan) || !string.IsNullOrEmpty(model.Unit) || !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Street) || !string.IsNullOrEmpty(model.LinkMan) || !string.IsNullOrEmpty(model.LinkTel))
                {
                    if (info["PlanID"] == null)
                    {
                        model.TaskID = Quota.TaskID;
                        model.QuotaCode = Quota.QuotaCode;
                        lst.Add(model);
                    }
                    else
                    {
                        var pid = int.Parse(info["PlanID"].ToString());
                        pids.Add(pid);
                        var p = qp.FirstOrDefault(it => it.PlanID == pid);
                        p.Name = model.Name;
                        p.Street = model.Street;
                        p.LinkMan = model.LinkMan;
                        p.LinkTel = model.LinkTel;
                        p.Unit = model.Unit;
                        p.ProgressPlan = model.ProgressPlan;
                        p.ProgressInfo = model.ProgressInfo;
                        p.Remarks = model.Remarks;
                        p.PlanData = model.PlanData;
                        p.PState = model.PState;
                        p.Tactic = model.Tactic;
                    }
                    index++;
                }

         
            }
            var Qt = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
            if (index > 0)
            {
                if (Qt == null)
                {
                    var model = new Yqd_QuotaTable();
                    model.TaskID = Quota.TaskID;
                    model.QuotaCode = Quota.QuotaCode;
                    model.FieldIDs = "";
                    model.TableType = Enm.清单类别.设置清单;
                    model.Instime = DateTime.Now;
                    model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                    model.TState = Enm.审核状态.同意;
                    ctx.Yqd_QuotaTable.Add(model);
                }
                else
                {
                    Qt.TableType = Enm.清单类别.设置清单;
                    Qt.TState = Enm.审核状态.同意;
                    Qt.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                }
                if (pids.Count() > 0)
                {
                    ctx.Yqd_QuotaPlan.RemoveRange(qp.Where(it=>!pids.Contains(it.PlanID)));
                }

            }
        

            ctx.Yqd_QuotaPlan.AddRange(lst);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public IActionResult GetQuotaPlanList()
        {
            var QuotaCode = Form.GetString("QuotaCode");
            var QPList = ctx.Yqd_QuotaPlan.Where(it => it.QuotaCode == QuotaCode).OrderBy(it => it.Tactic).ToList();
            var arr = new ArrayList();
            foreach (var QP in QPList)
            {
                arr.Add(new
                {
                    QP.PlanID,
                    QP.Name,
                    QP.Street,
                    QP.LinkMan,
                    QP.LinkTel,
                    QP.Unit,
                    QP.ProgressPlan,
                    QP.ProgressInfo,
                    QP.Remarks,
                    QP.PState,
                    QP.PlanData
                });

            }

            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }
        [User]
        public IActionResult AddTaskPlanQuestion()
        {
            var TaskID = Form.GetLong("TaskID");
            var datas = Form.GetString("datas").ToJArray();
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);


            if (Task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "指标信息不存在"
                });
            }
            var qp = ctx.Yqd_TaskPlanQuestion.Where(it => it.TaskID == TaskID);
            var lst = new List<Yqd_TaskPlanQuestion>();
            foreach (var info in datas)
            {
                if (info["ID"] == null)
                {
                    var model = new Yqd_TaskPlanQuestion
                    {
                        TaskID = Task.TaskID,
                        Question = info["Question"].ToString(),
                        Measure = info["Measure"].ToString(),
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        InsTime = DateTime.Now
                    };

                    lst.Add(model);
                }
                else
                {
                    var id = int.Parse(info["ID"].ToString());
                    var q = qp.FirstOrDefault(it => it.ID == id);
                    q.Question = info["Question"].ToString();
                    q.Measure = info["Measure"].ToString();
                    q.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                }
            }
            ctx.Yqd_TaskPlanQuestion.AddRange(lst);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });



        }
        [User]
        public IActionResult GetTaskPlanQuestionList()
        {
            var TaskID = Form.GetLong("TaskID");
            var QPList = ctx.Yqd_TaskPlanQuestion.Where(it => it.TaskID == TaskID).OrderBy(it => it.InsTime).ToList();
            var arr = new ArrayList();
            foreach (var QP in QPList)
            {

                arr.Add(new
                {
                    QP.ID,
                    QP.Question,
                    QP.Measure,
                    InsTime = QP.InsTime.ToString("yyyy-MM-dd")
                });
            }

            return this.ToJson(new
            {
                success = true,
                data = arr
            });
        }

        [User]
        public IActionResult DelTaskPlanQuestion()
        {
            var ID = Form.GetLong("ID");
            var Tpq = ctx.Yqd_TaskPlanQuestion.FirstOrDefault(it => it.ID == ID);

            if (Tpq == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "问题不存在"
                });
            }
            ctx.Yqd_TaskPlanQuestion.Remove(Tpq);
            ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public IActionResult GetTaskN_O()
        {
            var TaskID = Form.GetLong("TaskID");
            var qml = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var qmcode = qml.Select(it => it.QuotaCode);

            var QuotaList = ctx.Yqd_Quota.Where(it => it.TaskID == TaskID && it.IsShow).ToList();
            var Milestone = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow).ToList();

            var QuotaList_N = ctx.Yqd_QuotaNew.Where(it => it.TaskID == TaskID && it.IsShow && qmcode.Contains(it.QuotaCode)).ToList();
            var Milestone_N = ctx.Yqd_MilestoneNew.Where(it => it.TaskID == TaskID && it.IsShow && qmcode.Contains(it.TaskQuotaCode)).ToList();

            var Taskinfo = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var arr = new ArrayList();
            var Narr = new ArrayList();
            foreach (var Q in QuotaList)
            {
                var qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                arr.Add(new
                {
                    Q.ds,
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    MList = qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }),
                    MsgList = qml.Where(it => it.QuotaCode == Q.QuotaCode && it.IsShow).Select(it => new
                    {
                        it.ds,
                        it.Msg
                    })
                });
            }

            foreach (var Q in QuotaList_N)
            {
                var qm = Milestone_N.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                var oqm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                //if (qm.Count() ==0)
                //{
                //    qm = Milestone.Where(it => it.TaskQuotaCode == Q.QuotaCode).OrderBy(it => it.MilestoneTime).ToList();
                //}
                Narr.Add(new
                {
                    Q.ds,
                    Q.QuotaName,
                    Q.QuotaCode,
                    Q.ValueUnit,
                    Q.QuotaType,
                    Q.ValueType,
                    Q.StartValue,
                    Q.CurrentValue,
                    Q.TargetValue,
                    Q.Calucation,
                    MList = qm.Count() == 0 ? (oqm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    })) : (qm.Select(it => new
                    {
                        it.MilestoneTime,
                        it.TargetValue,
                        MT = it.MilestoneTime.ToString("M月")
                    }))

                });
            }

            return this.ToJson(new
            {
                success = true,
                Taskinfo.TaskName,
                data_O = arr,
                data_N = Narr
            });

        }

        [User]
        public IActionResult upNewsData()
        {
            var TaskID = Form.GetLong("TaskID");

            var QuotaList = ctx.Yqd_Quota.Where(it => it.TaskID == TaskID && it.IsShow);
            var NQuotaList = ctx.Yqd_QuotaNew.Where(it => it.TaskID == TaskID && it.IsShow);
            var MilestoneList = ctx.Yqd_Milestone.Where(it => it.TaskID == TaskID && it.IsShow);
            var NMilestoneList = ctx.Yqd_MilestoneNew.Where(it => it.TaskID == TaskID && it.IsShow);
            var qMsg = ctx.Yqd_QuotaMsg.Where(it => it.TaskID == TaskID);
            var Task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var AQL = new List<Yqd_Quota>();
            var AML = new List<Yqd_Milestone>();
            foreach (var Q in QuotaList)
            {
                var isQMsg = qMsg.Any(it => it.QuotaCode == Q.QuotaCode && it.TField == "Yqd_Quota");

                if (isQMsg)
                {
                    var NQ = NQuotaList.FirstOrDefault(it => it.QuotaCode == Q.QuotaCode);
                    Q.IsShow = false;

                    if (NQ.QuotaID == Q.QuotaID)
                    {
                        Q.QuotaName = NQ.QuotaName;
                        Q.QuotaCode = NQ.QuotaCode;
                        Q.TaskID = NQ.TaskID;
                        Q.QuotaID = NQ.QuotaID;
                        Q.QuotaType = NQ.QuotaType;
                        Q.TargetValue = NQ.TargetValue;
                        Q.CurrentValue = NQ.CurrentValue;
                        Q.StartValue = NQ.StartValue;
                        Q.ValueType = NQ.ValueType;
                        Q.ValueUnit = NQ.ValueUnit;
                        Q.QuotaDesc = NQ.QuotaDesc;
                        Q.Calucation = NQ.Calucation;
                        Q.ds = NQ.ds;
                        Q.CreateTime = NQ.CreateTime;
                        Q.Tactic = NQ.Tactic;
                        Q.IsShow = NQ.IsShow;
                        Q.Creator = NQ.Creator;
                        Q.InsTime = NQ.InsTime;

                    }
                    else
                    {
                        AQL.Add(new Yqd_Quota
                        {
                            QuotaName = NQ.QuotaName,
                            QuotaCode = NQ.QuotaCode,
                            TaskID = NQ.TaskID,
                            QuotaID = NQ.QuotaID,
                            QuotaType = NQ.QuotaType,
                            TargetValue = NQ.TargetValue,
                            CurrentValue = NQ.CurrentValue,
                            StartValue = NQ.StartValue,
                            ValueType = NQ.ValueType,
                            ValueUnit = NQ.ValueUnit,
                            QuotaDesc = NQ.QuotaDesc,
                            Calucation = NQ.Calucation,
                            ds = NQ.ds,
                            CreateTime = NQ.CreateTime,
                            Tactic = NQ.Tactic,
                            IsShow = NQ.IsShow,
                            Creator = NQ.Creator,
                            InsTime = NQ.InsTime
                        });

                    }
                    NQ.IsShow = false;
                }

                var isMMsg = qMsg.Any(it => it.QuotaCode == Q.QuotaCode && it.TField == "Yqd_Milestone");

                if (isMMsg)
                {
                    var NML = NMilestoneList.Where(it => it.TaskQuotaCode == Q.QuotaCode);
                    var ML = MilestoneList.Where(it => it.TaskQuotaCode == Q.QuotaCode);
                    foreach (var NM in NML)
                    {

                        AML.Add(new Yqd_Milestone
                        {
                            TaskID = NM.TaskID,
                            MilestoneID = NM.MilestoneID,
                            TaskQuotaCode = NM.TaskQuotaCode,
                            TargetValue = NM.TargetValue,
                            MilestoneTime = NM.MilestoneTime,
                            ds = NM.ds,
                            IsShow = NM.IsShow,
                            InsTime = NM.InsTime,
                            Tactic = NM.Tactic,
                            Creator = NM.Creator
                        });
                        NM.IsShow = false;
                    }

                    foreach (var M in ML)
                    {
                        M.IsShow = false;
                    }

                }

            }
            ctx.Yqd_Quota.AddRange(AQL);
            ctx.Yqd_Milestone.AddRange(AML);
            Task.TaskStatus = (int)Enm.任务状态.未考核;
            if (TaskID > 0)
            {

                var sql = string.Format("update Yqd_QuotaMsg set IsShow=0 where TaskID in ({0})", TaskID);
                ctx.Database.ExecuteSql(sql);
            }

            var r = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true
            });



        }

        [User]

        public IActionResult AddTaskError(Yqd_TaskError model)
        {
            var task = ctx.Yqd_Task.FirstOrDefault(it=>it.TaskID== model.TaskID);
            if (task == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "任务信息不存在"
                });
            }
            if (model.EvaluateInfoID > 0)
            {
                var ise = ctx.Yqd_EvaluateInfo.Any(it=>it.ID==model.EvaluateInfoID);
                if (!ise)
                {
                    return this.ToJson(new
                    {
                        success = false,
                        msg = "该条考核不存在"
                    });
                }
            }
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            task.TaskStatus = (int)任务状态.未考核;
            ctx.Yqd_TaskError.Add(model);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                ret
            });

        }

        [User]
        public IActionResult DelTaskError()
        {
            var ID = Form.GetLong("ID");
            var TaskE = ctx.Yqd_TaskError.FirstOrDefault(it => it.ID == ID);
            if (TaskE != null)
            {
                var task = ctx.Yqd_Task.FirstOrDefault(it=>it.TaskID== TaskE.TaskID);
                //var er=ctx
                task.TaskStatus = (int)任务状态.未考核; ;
                ctx.Yqd_TaskError.Remove(TaskE);
            }
            var ret = ctx.SaveChanges();
            //var ret = ctx.Database.ExecuteSql("delete from Yqd_TaskError where ID={0}", ID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
           
        }

        public IActionResult Test()
        {
            //   public JObject workNotification(string organizationCodes, string receiverIds, int tenantId,string bizMsgId, string msg)
            // var msg = "{'msgtype':'text','text':{'content': '给吴剑飞和金梦娇的测试消息'}}";


            //var msg = JObject.FromObject(new {
            //    msgtype ="text",
            //    text= JObject.FromObject(new {
            //        content= "给吴剑飞和金梦娇的测试消息"
            //    })
            //}).ToString();

            //var arr =new ArrayList();
            //arr.Add(new
            //{
            //    key = "效能指数",
            //    value= "83.71"
            //}) ;
            //arr.Add(new
            //{
            //    key = "全市排名",
            //    value = "14"
            //});

            var Rank = ctx.Yqd_Rank.FirstOrDefault(it => it.RankID == 1699);
            var msg = ddService.GetNotification_OA(Rank);
            var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == Rank.UnitCode);

            //I9Fmrp36JM5W0FJ3qP12oO4o06HYx30Ya6KD427l
            //GoJ8TI7569LeaaE7X33etAt920eP15kSr17AldUP

            var user = ctx.Yqd_User.Where(it => it.UnitCode == unit.OrganizationCode && it.AccountId > 0 && ("," + it.Roles + ",").Contains("," + (int)角色类型.部门联络员 + ","));


            var receiverIds = string.Join(",", user.Select(it => it.AccountId));

            //var data = ddService.workNotification("", receiverIds, Rank.RankID+"_1", msg);
            return this.ToJson(new
            {
                success = true,
                //   data = data
            });
        }

        [User]
        public ActionResult Import()
        {
            var fn = Form.GetString("fn");
            var TaskID = Form.GetLong("TaskID",0);
            var QuotaCode = Form.GetString("QuotaCode");
            var q = ctx.Yqd_Quota.FirstOrDefault(it=>it.QuotaCode== QuotaCode);
            if (TaskID == 0)
            {
                TaskID = q.TaskID;
            }

            var path = Config.Yqdpath("/");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            
            FileInfo file = new FileInfo(path + fn);
            Logs.Warning<ZLDHomeController>("file:"+path + fn);
            Logs.Warning<ZLDHomeController>("FullName:" + file.FullName);
            var index = 0;
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheet1"];
                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                   // var fields = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID)).OrderBy(it => it.Tactic).Select(it => new { it.FieldID, it.Name }).ToList();
                    var record = new Dictionary<string, string>();
                    var yqpl =new List<Yqd_QuotaPlan>();
                    for (var row = 2; row <= rowCount; row++)
                    {
                        record.Clear();
                        var model = new Yqd_QuotaPlan();
                        model.TaskID = TaskID;
                        model.QuotaCode = QuotaCode;

                        model.Name= worksheet.Cells[row, 1].Value.ToString().Trim();
                        model.Street = worksheet.Cells[row, 2].Value.ToString().Trim();
                        model.Unit = worksheet.Cells[row, 3].Value.ToString().Trim();
                        model.LinkMan = worksheet.Cells[row, 4].Value.ToString().Trim();
                        model.LinkTel = worksheet.Cells[row, 5].Value.ToString().Trim();
                        var P=  worksheet.Cells[row, 6].Value.ToString().Trim();
                        model.PState = P== "未启动"?清单状态.未启动:(P == "推进中" ? 清单状态.推进中: 清单状态.已完成);
                        model.ProgressPlan= worksheet.Cells[row, 7].Value.ToString().Trim();
                        model.ProgressInfo = worksheet.Cells[row, 8].Value.ToString().Trim();
                        model.Remarks = worksheet.Cells[row, 9].Value.ToString().Trim();
                        //for (var col = 1; col < ColCount; col++)
                        //{
                        //    var nt = worksheet.Cells[row, col].Value.ToString().Trim();
                        //    //var f = fields.FirstOrDefault(it => it.Name.Trim() == nt);
                        //    //if (f != null) record.Add(f.FieldID, nt);
                        //}
                        //if (record.Count() > 0) model.Content = JObject.FromObject(record).ToString();
                        //model.Instime = DateTime.Now;
                        //model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
                        //model.UnitCode = WxUser.LogonInfo.UnitCode;
                        // ctx.Yqd_SpecialTarget.Add(model);
                        model.Tactic = index;
                        if (!string.IsNullOrEmpty(model.Remarks) || !string.IsNullOrEmpty(model.ProgressInfo) || !string.IsNullOrEmpty(model.ProgressPlan) || !string.IsNullOrEmpty(model.Unit) || !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Street) || !string.IsNullOrEmpty(model.LinkMan) || !string.IsNullOrEmpty(model.LinkTel))
                        {
                            // ctx.Yqd_QuotaPlan.Add(model);
                            yqpl.Add(model);
                            index++;
                        }
                          
                    }

                    if (yqpl.Count() > 0)
                    {
                        ctx.Yqd_QuotaPlan.AddRange(yqpl);
                        var Qt = ctx.Yqd_QuotaTable.FirstOrDefault(it => it.QuotaCode == QuotaCode);
                        if (index > 0)
                        {
                            if (Qt == null)
                            {
                                var model = new Yqd_QuotaTable();
                                model.TaskID =TaskID;
                                model.QuotaCode =QuotaCode;
                                model.FieldIDs = "";
                                model.TableType = Enm.清单类别.设置清单;
                                model.Instime = DateTime.Now;
                                model.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                                model.TState = Enm.审核状态.同意;
                                ctx.Yqd_QuotaTable.Add(model);
                            }
                            else
                            {
                                Qt.TableType = Enm.清单类别.设置清单;
                                Qt.TState = Enm.审核状态.同意;
                                Qt.AddEmployeeCode = WxUser.LogonInfo.EmployeeCode;
                            }
                        }

                    }

                   
                    var ret = ctx.SaveChanges();
                    return this.ToJson(new
                    {
                        success = true,
                        ret
                    });
                }
            }
            return this.ToJson(new
            {
                success = false
            });
        }


    }
}
